package me.green.dao;

import me.green.bean.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户Dao
 *
 * @author green
 */
public class UserDao {


    /**
     * 根据用户名和密码得到用户的信息
     *
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    public User login(String userName, String password) {
        User userInfo = null;
        String sql = "select * from user where username=? and password=?";
        Connection conn = null;
        try {
            conn = BaseDB.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, userName);
            ps.setString(2, password);

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                userInfo = new User();
                userInfo.setId(rs.getInt(1));
                userInfo.setUserName(rs.getString(2));
                // userInfo.setPassword(rs.getString(3));
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDB.release(conn);
        }
        return userInfo;
    }


    /**
     * 修改密码
     *
     * @param uid
     * @param oldPwd
     * @param newPwd
     * @return
     */
    public boolean updatePassword(int uid, String oldPwd, String newPwd) {
        Connection conn = null;
        try {
            conn = BaseDB.getConnection();
            String sql = "update user set password=? where id=? and password=? ";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, newPwd);
            ps.setInt(2, uid);
            ps.setString(3, newPwd);
            int rows = ps.executeUpdate();
            return rows > 0 ? true : false;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDB.release(conn);
        }
        return false;
    }


}
